/*
-------------------------------------------------------------------
BIE is Copyright 2001-2003 Brunswick Corp.
-------------------------------------------------------------------
Please read the legal notices (docs/legal.txt) and the license
(docs/bie_license.txt) that came with this distribution before using
this software.
-------------------------------------------------------------------
*/
package com.webdeninteractive.sbie.v1_1.util;

import java.util.*;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class SelectLoop {

    Context context;
    PreparedStatement statement;
    ArrayList handlers;
    
    private void init( PreparedStatement ps, Context ctx ) {
        this.context = ctx;
        this.statement = ps;
        handlers = new ArrayList();
    }

    public SelectLoop( PreparedStatement ps, Context ctx ) {
        init( ps, ctx );
    }

    public SelectLoop( PreparedStatement ps ) {
        Context c = new Context();
        init( ps, c );
    }
    
    public void clearHandlers() {
        handlers = new ArrayList();
    }

    public void addHandler( SelectLoopHandler handler ) {
        handlers.add( handler );
    }

    public List getHandlers() {
        return handlers;
    }

    public Context getContext() {
        return context;
    }

    public void execute() 
        throws SQLException
    {
        ResultSet rs = null;
        try {
            rs = statement.executeQuery();
            while( rs.next() ) {
                Iterator it = handlers.iterator();
                while ( it.hasNext() ) {
                    SelectLoopHandler h = (SelectLoopHandler)it.next();
                    h.each( context, rs );
                }
            }

        } finally {
            try {
                if (rs!=null) { rs.close(); }
            } catch (Exception e) { /*ignore*/ }
        }
        
    }

    // --

    public class Context {
        HashMap attr = new HashMap();
        public Object getAttribute( String name ) {
            return attr.get(name);
        }
        public void setAttribute( String name, Object value ) {
            attr.put(name, value);
        }
    }

}
